package com.souku.finance.application.utils;

import android.os.Build;

import com.souku.finance.application.http.UrlConstact;

import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Set;

/**
 * Created by Android on 2016/12/29.
 */

public class ParamUtil {

    public static HashMap<String, String> getParams() {
        HashMap<String, String> map = new HashMap<>();
        if (ShareUtil.getInstance().getString(Constant.Token) != null) {
            map.put(Constant.Token, ShareUtil.getInstance().getString(Constant.Token));
        }
        //加入公共参数
        return map;
    }

    public static HashMap<String, String> getHeaders() {
        HashMap<String, String> hashMap = new HashMap<String, String>();
        hashMap.put("MMA-OS-N", "Android");
        hashMap.put("MMA-OS-V", Build.VERSION.RELEASE);
        hashMap.put("MMA-MB-BD", Build.MODEL);
        //hashMap.put("MMA-EQ-ID", ShareUtil.getInstance().getString(Constant.DeviceId));
        //hashMap.put("MMA-APP-V",ShareUtil.getInstance().getString(Constant.Version));
        return hashMap;
    }

    public static HashMap<String, String> getSing(HashMap<String, String> hashMap) {
        Set<String> set = hashMap.keySet();
        List<String> list = new ArrayList<>();
        Iterator<String> it = set.iterator();
        while (it.hasNext()) {
            list.add(it.next());
        }
        Collections.sort(list);
        String million = ShareUtil.getInstance().getString(Constant.Servertime);
        if (million == null) {
            million = System.currentTimeMillis() + "";
        }
        String str = "";
        for (int i = 0; i < list.size(); i++) {
            str += hashMap.get(list.get(i));
        }
        str += million;
        str += UrlConstact.MD5KEY;
        hashMap.put("timeStamp", million);
        hashMap.put("sign", md5(str));
        return hashMap;
    }

    public static String md5(String string) {
        byte[] hash;
        try {
            hash = MessageDigest.getInstance("MD5").digest(string.getBytes("UTF-8"));
        } catch (NoSuchAlgorithmException e) {
            throw new RuntimeException("Huh, MD5 should be supported?", e);
        } catch (UnsupportedEncodingException e) {
            throw new RuntimeException("Huh, UTF-8 should be supported?", e);
        }
        StringBuilder hex = new StringBuilder(hash.length * 2);
        for (byte b : hash) {
            if ((b & 0xFF) < 0x10) hex.append("0");
            hex.append(Integer.toHexString(b & 0xFF));
        }
        System.out.println(hex.toString());
        return hex.toString();
    }
}
